/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import Clases.Empleado;
import Clases.Pago;
import Clases.crearPDF;
import Control.ControlEmpleado;
import Control.ControlPago;
import com.csvreader.CsvWriter;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 *
 * @author Jose Rafael
 */
public class OpcionesReporteBanco extends javax.swing.JFrame {

    private static OpcionesReporteBanco instancia = null;
    static ButtonGroup grupo = new ButtonGroup();
    DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    private ImageIcon iconoError;
    private File archivo = null;
    ControlPago controlP = ControlPago.obtenerInstancia();

    public OpcionesReporteBanco() {
        initComponents();
        grupo.add(jRadioButtonExcel);
        grupo.add(jRadioButtonPDF);
        jRadioButtonExcel.setSelected(true);
    }

    public static OpcionesReporteBanco obtenerInstancia() {
        if (instancia == null) {
            instancia = new OpcionesReporteBanco();
        }
        return instancia;
    }

    public void init() {
        setTitle("Reporte de Pago de Bancos");
        setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        inicioTooltops();
        this.limpiar();
        this.setVisible(true);
    }

    private void inicioTooltops() {
        iconoError = new ImageIcon(getClass().getResource("/Imagenes/warning.png"));

        jLabelValidaRuta.setIcon(iconoError);
        jLabelValidaRuta.setToolTipText("Debe seleccionar una ruta para guardar el archivo.");
        ocultarLabels();
    }

    private void ocultarLabels() {
        jLabelValidaRuta.setVisible(false);
    }

    public void limpiar() {
        jLabelRuta.setText(" ");
        archivo = null;
        ocultarLabels();
    }

    private boolean validarReporte() {
        ocultarLabels();
        boolean itsOk = true;
        if (jLabelRuta.getText()==" ") {
            jLabelValidaRuta.setVisible(true);
            itsOk = false;
        }
        return itsOk;
    }

    void generarReporteGeneralBanco(int opc) throws IOException {

        Date fecha = new Date();
        String fechaString = dateFormat.format(fecha);
        ControlEmpleado ce = ControlEmpleado.obtenerInstancia();
        ArrayList<Empleado> empleados = ce.obtenerEmpleadosBancarios();
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Elegir Destino");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (opc == 1) {
            String ruta = jLabelRuta.getText() + fechaString + "_reporteBanco_" + ".csv";
            boolean existe = new File(ruta).exists();
            if (existe) {
                File ficheroUsuarios = new File(ruta);
                ficheroUsuarios.delete();
            }
            CsvWriter writer = new CsvWriter(new FileWriter(ruta, true), ';');
            try {
                writer.writeRecord(new String[]{"TECNO CARROCERIAS EBEN EZER S.A"});
                writer.writeRecord(new String[]{"", "PLANILLA AL DIA" + String.valueOf(fecha.getDate()) + "DEL MES " + String.valueOf(fecha.getMonth() + 1)});
                writer.writeRecord(new String[]{"#", "NOMBRE", "Cedula", "Cuenta", "TOTAL"});
                double total=0;
                for (Empleado EmpleadoTemp : empleados) {
                    ArrayList<Date> pago = controlP.getPago();
                    java.sql.Date sqlDate1 = new java.sql.Date((pago.get(0)).getTime());
                    java.sql.Date sqlDate2 = new java.sql.Date((pago.get(1)).getTime());
                    Pago pagoActual = controlP.getPagoActual(EmpleadoTemp.getNumEmpleado(), sqlDate1, sqlDate2);
                    double temp = pagoActual.getSalarioBase();
                    total+=temp;

                    writer.writeRecord(new String[]{String.valueOf(EmpleadoTemp.getNumEmpleado()),
                        EmpleadoTemp.getNombre() + " " + EmpleadoTemp.getApellido1() + " " + EmpleadoTemp.getApellido2(),
                        String.valueOf(EmpleadoTemp.getCedula()),
                        EmpleadoTemp.getNumCuenta(),
                        String.valueOf(temp)});
                }
                writer.writeRecord(new String[]{"","","","TOTALES",String.valueOf(total)});
                    
                

            } catch (IOException e) {
            }
            writer.close();
            JOptionPane.showMessageDialog(null, "csv generado con toda la información del reporte de los pagos bancarios dia " + String.valueOf(fecha.getDate()) + " del mes: "
                    + String.valueOf(fecha.getMonth() + 1), "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            dispose();

        } else {

            ArrayList<Date> pago = controlP.getPago();
            java.sql.Date sqlDate1 = new java.sql.Date((pago.get(0)).getTime());
            java.sql.Date sqlDate2 = new java.sql.Date((pago.get(1)).getTime());
            String ruta = archivo.getPath();
            crearPDF pdf = new crearPDF();
            ArrayList<String> contenidoPDF = new ArrayList<String>();
            contenidoPDF.add(" ");
            contenidoPDF.add(" ");
            contenidoPDF.add("Reporte Pago Bancario\nFecha de Reporte: " + String.valueOf(fecha.getDay()) + "/" + String.valueOf(fecha.getMonth() + 1) + "/" + String.valueOf(fecha.getYear() + 1900));
            double total=0;
            for (Empleado EmpleadoTemp : empleados) {
                Pago pagoActual = controlP.getPagoActual(EmpleadoTemp.getNumEmpleado(), sqlDate1, sqlDate2);
                double temp2 = pagoActual.getSalarioBase();
                total+=temp2;

                contenidoPDF.add("Nombre del empleado: " + EmpleadoTemp.getNombre() + " " + EmpleadoTemp.getApellido1() + " " + EmpleadoTemp.getApellido2());
                contenidoPDF.add("Número del empleado: " +String.valueOf(EmpleadoTemp.getNumCuenta()));
                contenidoPDF.add("Cédula: " + EmpleadoTemp.getCedula());
                contenidoPDF.add("Cuenta: "+String.valueOf(EmpleadoTemp.getNumCuenta()));
                contenidoPDF.add("Salario base : " + temp2);
                contenidoPDF.add(" ");
                contenidoPDF.add(" ");
            }
            contenidoPDF.add("Totales: "+ total);
            pdf.crearPDF(String.valueOf(fecha.getDate()) + String.valueOf(fecha.getMonth() + 1), "Pago Bancario", contenidoPDF, ruta);
            JOptionPane.showMessageDialog(null, "PDF generado con toda la información del reporte de la caja dia " + String.valueOf(fecha.getDate()) + " del mes: "
                    + String.valueOf(fecha.getMonth() + 1), "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabelValidaRuta = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabelRuta = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jRadioButtonExcel = new javax.swing.JRadioButton();
        jRadioButtonPDF = new javax.swing.JRadioButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Ruta del archivo: ");

        jLabelValidaRuta.setText("x");

        jButton1.setText("Buscar ruta");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel3.setText("Formato del reporte: ");

        jRadioButtonExcel.setText("Excel(.csv)");

        jRadioButtonPDF.setText("PDF(.pdf)");

        jButton2.setText("Crear");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Salir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jRadioButtonPDF)
                            .addComponent(jRadioButtonExcel)
                            .addComponent(jLabel3)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jButton2)
                                .addGap(181, 181, 181)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton3)
                                    .addComponent(jLabelValidaRuta))))
                        .addContainerGap(59, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)
                        .addGap(37, 37, 37))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabelValidaRuta))
                .addGap(32, 32, 32)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(30, 30, 30)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(jRadioButtonExcel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRadioButtonPDF)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            archivo = fc.getSelectedFile();
            if (archivo.isDirectory()) {
                jLabelRuta.setText(archivo.toString() + File.separator);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (validarReporte()) {

            if (jRadioButtonExcel.isSelected()) {
                try {
                    generarReporteGeneralBanco(1);
                } catch (IOException ex) {
                    Logger.getLogger(OpcionesReporteBanco.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    generarReporteGeneralBanco(2);
                } catch (IOException ex) {
                    Logger.getLogger(OpcionesReporteBanco.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OpcionesReporteBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OpcionesReporteBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OpcionesReporteBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OpcionesReporteBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OpcionesReporteBanco().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelRuta;
    private javax.swing.JLabel jLabelValidaRuta;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButtonExcel;
    private javax.swing.JRadioButton jRadioButtonPDF;
    // End of variables declaration//GEN-END:variables
}
